<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
        <p>{{ isLogin ? '欢迎回来，请登录您的账户' : '创建新账户，开始使用系统' }}</p>
      </div>

      <!-- 登录表单 -->
      <form v-if="isLogin" @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="loginId">用户名/邮箱</label>
          <input
            id="loginId"
            v-model="loginForm.loginId"
            type="text"
            placeholder="请输入用户名或邮箱"
            required
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            required
          />
        </div>

        <div class="form-group checkbox-group">
          <label class="checkbox-label">
            <input
              v-model="loginForm.rememberMe"
              type="checkbox"
            />
            <span class="checkmark"></span>
            记住我
          </label>
        </div>

        <button type="submit" class="submit-btn" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>

      <!-- 注册表单 -->
      <form v-else @submit.prevent="handleRegister" class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="registerForm.username"
            type="text"
            placeholder="请输入用户名（3-20个字符）"
            required
          />
        </div>

        <div class="form-group">
          <label for="email">邮箱</label>
          <input
            id="email"
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            required
          />
        </div>

        <div class="form-group">
          <label for="realName">真实姓名</label>
          <input
            id="realName"
            v-model="registerForm.realName"
            type="text"
            placeholder="请输入真实姓名（可选）"
          />
        </div>

        <div class="form-group">
          <label for="phone">手机号</label>
          <input
            id="phone"
            v-model="registerForm.phone"
            type="tel"
            placeholder="请输入手机号（可选）"
          />
        </div>

        <div class="form-group">
          <label for="regPassword">密码</label>
          <input
            id="regPassword"
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            required
          />
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            id="confirmPassword"
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            required
          />
        </div>

        <button type="submit" class="submit-btn" :disabled="loading">
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </form>

      <!-- 切换登录/注册 -->
      <div class="switch-mode">
        <p v-if="isLogin">
          还没有账户？
          <a href="#" @click.prevent="toggleMode">立即注册</a>
        </p>
        <p v-else>
          已有账户？
          <a href="#" @click.prevent="toggleMode">立即登录</a>
        </p>
      </div>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>

      <!-- 成功提示 -->
      <div v-if="successMessage" class="success-message">
        {{ successMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { authAPI } from '@/api/auth'

export default {
  name: 'Login',
  data() {
    return {
      isLogin: true,
      loading: false,
      errorMessage: '',
      successMessage: '',
      loginForm: {
        loginId: '',
        password: '',
        rememberMe: false
      },
      registerForm: {
        username: '',
        email: '',
        realName: '',
        phone: '',
        password: '',
        confirmPassword: ''
      }
    }
  },
  methods: {
    // 切换登录/注册模式
    toggleMode() {
      this.isLogin = !this.isLogin
      this.clearMessages()
      this.resetForms()
    },

    // 处理登录
    async handleLogin() {
      this.clearMessages()
      
      if (!this.loginForm.loginId || !this.loginForm.password) {
        this.errorMessage = '请填写完整的登录信息'
        return
      }

      this.loading = true

      try {
        const response = await authAPI.login(this.loginForm)
        const { token, userInfo, message } = response.data

        // 保存token和用户信息到本地存储
        localStorage.setItem('satoken', token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))

        this.successMessage = message || '登录成功'
        
        // 延迟跳转到首页
        setTimeout(() => {
          this.$router.push('/')
        }, 1000)

      } catch (error) {
        console.error('登录失败:', error)
        this.errorMessage = error.response?.data?.message || '登录失败，请检查用户名和密码'
      } finally {
        this.loading = false
      }
    },

    // 处理注册
    async handleRegister() {
      this.clearMessages()
      
      // 表单验证
      if (!this.validateRegisterForm()) {
        return
      }

      this.loading = true

      try {
        const response = await authAPI.register(this.registerForm)
        const { message } = response.data

        this.successMessage = message || '注册成功，请登录'
        
        // 延迟切换到登录模式
        setTimeout(() => {
          this.toggleMode()
        }, 2000)

      } catch (error) {
        console.error('注册失败:', error)
        this.errorMessage = error.response?.data?.message || '注册失败，请重试'
      } finally {
        this.loading = false
      }
    },

    // 验证注册表单
    validateRegisterForm() {
      const { username, email, password, confirmPassword } = this.registerForm

      if (!username || !email || !password || !confirmPassword) {
        this.errorMessage = '请填写所有必填字段'
        return false
      }

      if (username.length < 3 || username.length > 20) {
        this.errorMessage = '用户名长度必须在3-20个字符之间'
        return false
      }

      if (password.length < 6) {
        this.errorMessage = '密码长度不能少于6位'
        return false
      }

      if (password !== confirmPassword) {
        this.errorMessage = '两次输入的密码不一致'
        return false
      }

      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(email)) {
        this.errorMessage = '请输入有效的邮箱地址'
        return false
      }

      return true
    },

    // 清除提示信息
    clearMessages() {
      this.errorMessage = ''
      this.successMessage = ''
    },

    // 重置表单
    resetForms() {
      this.loginForm = {
        loginId: '',
        password: '',
        rememberMe: false
      }
      this.registerForm = {
        username: '',
        email: '',
        realName: '',
        phone: '',
        password: '',
        confirmPassword: ''
      }
    }
  },

  // 组件挂载时检查是否已登录
  async mounted() {
    try {
      const response = await authAPI.checkLogin()
      if (response.data.isLogin) {
        this.$router.push('/')
      }
    } catch (error) {
      console.log('未登录状态')
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 8px;
  font-size: 28px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.form-group input {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.checkbox-group {
  flex-direction: row;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-label input[type="checkbox"] {
  margin-right: 8px;
  width: auto;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 14px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.switch-mode {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e1e5e9;
}

.switch-mode p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.switch-mode a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.switch-mode a:hover {
  text-decoration: underline;
}

.error-message {
  background: #fee;
  color: #c33;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #fcc;
  margin-top: 15px;
  font-size: 14px;
}

.success-message {
  background: #efe;
  color: #363;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #cfc;
  margin-top: 15px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
    margin: 10px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}
</style>